package com.example.webdownloadserver.job;

import com.example.webdownloadserver.base.TaskDownloadThreadPool;
import com.example.webdownloadserver.service.TaskCenterService;
import com.example.webdownloadserver.vo.TaskCenter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;


/**
 * 
 * <p>
 * 下载任务
 * </p>
 * @title DownloadJob.java
 * @package com.dnkj.download.task.job 
 * @author ying.xiao
 * @version 0.1 2020年12月5日
 */
@Component
public class DownloadJob {

	private Logger LOGGER = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private TaskCenterService taskCenterService;

	@Scheduled(cron = "0 0/2 * * * ?")
	public void execute() {
		LOGGER.info("开始处理下载任务...");
	
		Long taskId = 0L;
		try {
			// 当前活跃线程数
			int activeNum = TaskDownloadThreadPool.getActiveCount();
			// 根据线程池执行能力获取抓取任务数
			int idle = TaskDownloadThreadPool.getIdleNum();
			LOGGER.info("当前下载线程池空余线程数：" + idle);
			if (0 >= idle) {
				LOGGER.info("当前下载线程池有" + activeNum + "任务在执行，已经没有空余线程，等待下次轮询");
				return;
			}
			List<TaskCenter> list = taskCenterService.downloadTaskCenterList(idle);
			if (null != list && list.size() > 0) {
				LOGGER.info("需处理的下载记录共【" + list.size() + "】条");
				for (TaskCenter task : list) {
					taskId = task.getTaskId();
					TaskDownloadThreadPool.download(taskCenterService,task  );
				}
			} else {
				LOGGER.info("需处理的下载记录共【0】条");
			}
		} catch (Exception e) {
			LOGGER.error("处理下载记录出错---任务ID[" + taskId + "]:" + e, e);
		} catch (Throwable e) {
			LOGGER.error("处理下载记录出错---任务ID[" + taskId + "]:" + e, e);
		}

	}

}
